import APIZPZ from "../../../utils/apiZpz";
import Dialog from '@vant/weapp/dialog/dialog';

const HEADER = <any>{
  10: '待上门取件，请保持手机畅通',
  11: '物流运输中，请耐心等待',
  12: '您的订单已签收，即将开始质检，请耐心等待',
  13: '您的订单已开始质检，请耐心等待',
  20: '订单已关闭，未能与您达成交易，我们深表遗憾',
  21: '待退回，您的机器暂不支持回收',
  22: '已退回',
  30: '待确认交易，请尽快操作以防市场波动机器掉价',
  31: '待打款，请耐心等待',
  32: '打款失败，请修改收款信息后再次点击申请打款',
  33: '交易完成，回收款已汇入您的账户中',
  88: '异常关闭',
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',//订单id
    orderDetail: <any>{},//订单详情
    payeeVisible: false,//收款信息录入dialog
    account: '',//收款账户
    name: '',//收款人
    oldTime: 0,
    confirmPayeeDialogVisible: false,//确认收款信息dialog
    expressInfoVisible: false,//物流信息popup
    expressInfoList: <any>[],//物流信息跟踪列表
    collectMoneyVisible: false,//立即收钱dialog
    checkReturnAddressVisible: false,//选择退货地址
    addressList: <any>[],//地址列表 
    selectedAddress: <any>{},//选中的地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(data: any) {
    this.setData({
      orderId: data.id
    });
    this.getOrderDetail();
  },
  getOrderDetail() {
    APIZPZ.getOrderDetail(this.data.orderId).then((res: any) => {
      res.data.logistics.exparea = res.data.logistics.exparea.replace(/@/g, ' ');
      res.data.logistics.lnktelPrivacy = res.data.logistics.lnktel.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
      if (res.data.backLogistics) {
        res.data.backLogistics.exparea = res.data.backLogistics.exparea.replace(/@/g, ' ');
        res.data.backLogistics.lnktelPrivacy = res.data.backLogistics.lnktel.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
      }
      // res.data.ostat = 32;
      // res.data.rtnstat = 11;
      // res.data.brp = 999;
      res.data.ostatTitle = HEADER[res.data.ostat]
      if (res.data.ostat === 21 && res.data.rtnstat === 12) {
        res.data.ostatTitle = '待退回，我们将尽快给您发货'
      }
      this.setData({
        orderDetail: res.data
      })
      console.log(this.data.orderDetail)
    })
  },
  // 复制文本
  copyText(e: any) {
    const text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success() {
        wx.showToast({
          title: '复制成功',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  showPayeeInfoDialog() {
    this.setData({
      payeeVisible: true,
      account: this.data.orderDetail.payacc,
      name: this.data.orderDetail.payname,
    })
  },
  hidePayeeInfoDialog() {
    this.setData({
      payeeVisible: false,
      account: '',
      name: ''
    })
  },
  // 保存收款信息
  savePayee() {
    if (!this.data.account || !this.data.account.trim()) {
      wx.showToast({
        title: '请输入收款账户',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!this.data.name || !this.data.name.trim()) {
      wx.showToast({
        title: '请输入收款人姓名',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    APIZPZ.bindPayee(this.data.orderId, this.data.account, this.data.name).then(() => {
      this.setData({
        payeeVisible: false,
        account: '',
        name: '',
      });
      this.getOrderDetail();
    });
  },
  // 取消订单
  cancelOrder() {
    Dialog.confirm({
      title: '提示',
      message: `您确认要取消该订单吗`,
    })
      .then(() => {
        // on confirm
        APIZPZ.cancelOrder(this.data.orderId).then(() => {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          })
          this.getOrderDetail();
        })
      })
      .catch(() => {
        // on cancel
      });
  },
  showConfirmPayeeDialog() {
    this.setData({
      confirmPayeeDialogVisible: true
    })
  },
  hideConfirmPayeeDialog() {
    this.setData({
      confirmPayeeDialogVisible: false
    })
  },
  confirmPayeeInfo() {
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    APIZPZ.payAgain(this.data.orderId).then(() => {
      this.setData({
        confirmPayeeDialogVisible: false
      });
      this.getOrderDetail();
    })
    console.log('确认收款信息申请重新打款')
  },
  showExpressInfo() {
    APIZPZ.expressTrack(this.data.orderDetail.id, this.data.orderDetail.logistics.expno).then((res: any) => {
      res.data = res.data.map((item: any) => {
        let name = '';
        switch (item.opcode) {
          case '43':
          case '46':
          case '50':
          case '54':
            name = '已揽件';
            break;
          case '80':
          case '8000':
            name = '已签收';
            break;
          case '44':
            name = '配送中';
            break;
          default:
            name = '运输中';
        }
        item.opcodeName = name;
        item.remarkPhone = item.remark.match(/\d{11}/)
        item.remark = item.remark.split(/\d{11}/)
        return item;
      })
      this.setData({
        expressInfoVisible: true,
        expressInfoList: res.data
      })
    })
  },
  hideExpressInfo() {
    this.setData({
      expressInfoVisible: false
    });
  },
  callPhone(e: any) {
    console.log(e)
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone[0]
    })
  },
  toEvaluateDetail() {
    wx.navigateTo({ url: `/pages/my-order/order-detail/evaluate-detail/evaluate-detail?id=${this.data.orderDetail.id}` })
  },
  toEvaluateResult() {
    
    APIZPZ.getQualityList(this.data.orderId).then((res: any) => {
      console.log(res.data)
      if(res.data.length===1){
        console.log(res.data[0])
        wx.navigateTo({ url: `/pages/my-order/order-detail/quality/quality-detail/quality-detail?id=${this.data.orderId}&deviceId=${res.data[0].id}` });
      }else{
        wx.navigateTo({ url: `/pages/my-order/order-detail/quality/quality-list/quality-list?id=${this.data.orderId}` });
      }
    })
  },
  showCollectMoney() {
    this.setData({
      collectMoneyVisible: true
    })
  },
  hideCollectMoney() {
    this.setData({
      collectMoneyVisible: false
    })
  },
  collectMoney() {
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    APIZPZ.collectMoney(this.data.orderId).then(() => {
      this.setData({
        collectMoneyVisible: false
      });
      this.getOrderDetail();
    })
  },
  showCheckReturnAddress() {
    this.setData({
      checkReturnAddressVisible: true
    });
  },
  hideCheckReturnAddress() {
    this.setData({
      checkReturnAddressVisible: false,
      selectedAddress: {}
    });
  },
  //获取地址列表
  getAddressList() {
    APIZPZ.getAddressList().then((res: any) => {
      console.log(res.data)
      res.data = res.data.map((item: any) => {
        item.addressPreview = item.exparea.split('@').join(' ') + ' ' + item.expdtl;
        return item;
      })
      this.setData({
        addressList: res.data
      })
    })
  },
  addAddress() {
    wx.navigateTo({ url: '/pages/address/address-edit/address-edit' })
  },
  setSelectedAddress(e: any) {
    this.setData({
      selectedAddress: e.currentTarget.dataset.address
    })
  },
  // 狠心不买了保存退货地址
  savekReturnAddress(e: any) {
    if (!this.data.selectedAddress.id) {
      wx.showToast({
        title: '请选择退货地址',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    const time = new Date().getTime();
    if (time - this.data.oldTime < 1000) {
      return;
    }
    this.data.oldTime = time;
    APIZPZ.setReturnAddress(this.data.orderId, {
      exparea: this.data.selectedAddress.exparea,
      expdtl: this.data.selectedAddress.expdtl,
      lnker: this.data.selectedAddress.lnker,
      lnktel: this.data.selectedAddress.lnktel
    }, e.currentTarget.dataset.type).then(() => {
      this.hideCheckReturnAddress();
      this.getOrderDetail();
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddressList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})